<template>
  <div class="detail" ref="containerRef">
    <!-- 测试文件下载用 -->
    <!-- <a-button @click.stop="handleDownload" type="primary">下载</a-button> -->

    <div class="approve-content">
      <a-collapse :default-active-key="['1']" :bordered="false">
        <a-collapse-item header="任务详情" :key="defaultExpandkeys">
          <template #header>
            <div class="header-line">
              <span>任务详情</span>
              <a-link @click.stop="handleGoBackList">返回列表<icon-redo style="margin-left: 4px" /></a-link>
            </div>
          </template>
          <div class="task-detail">
            <div class="detail-item">
              <div class="item-title">用户信息：</div>
              <div class="item-content">
                {{ userInfo.username + '+' + userInfo.userPhone }}
              </div>
            </div>
            <div class="detail-item">
              <div class="item-title">任务ID：</div>
              <div class="item-content">{{ userInfo.taskId }}</div>
            </div>
            <!-- <div class="detail-item">
            <div class="item-title">审核状态：</div>
            <div class="item-content">{{userInfo.auditStatus}}</div>
          </div> -->
            <div class="detail-item">
              <div class="item-title">任务状态：</div>
              <div class="item-content">{{ userInfo.taskStatus }}</div>
            </div>
            <div class="detail-item" v-if="currentTask.taskStatus === '已取消'">
              <div class="item-title">取消时间：</div>
              <div class="item-content">{{ userInfo.cancelTime }}</div>
            </div>
            <div class="detail-item">
              <div class="item-title">创建时间：</div>
              <div class="item-content">{{ userInfo.createTime }}</div>
            </div>
            <div class="detail-item">
              <div class="item-title">所属需求：</div>
              <div class="item-content">{{ userInfo.demandName }}</div>
            </div>
            <div class="detail-item">
              <div class="item-title">执行人员：</div>
              <div class="item-content">{{ userInfo.executive }}</div>
            </div>
          </div>
        </a-collapse-item>
      </a-collapse>
      <div class="approved-container">
        <div class="approved-header flex-justify-between">
          <div class="title-line flex-justify-between" :class="{ 'head-flod': !expand.left }">
            <div>
              <span class="title-name">版本记录</span>
              <a-checkbox v-show="expand.left" @change="handleChangeAll" v-model="isAllChecked">全部</a-checkbox>
            </div>
            <span class="expand-icon">
              <icon-menu-fold v-show="expand.left" class="el-icon-s-fold" @click="expand.left = false" />
              <icon-menu-unfold v-show="!expand.left" class="el-icon-s-unfold" @click="expand.left = true" />
            </span>
          </div>
          <div class="center-header scrollbar-class">
            <div
              class="header-item"
              :class="{ 'active-file': index === currentFileIndex }"
              v-for="(item, index) in currentFileList.text_url"
              :key="index"
              :title="item.name"
            >
              <a-input
                size="small"
                ref="changeFileNameRef"
                @blur="handleEditBlur(item)"
                v-model="item.name"
                v-if="item.editing"
                style="width: 120px"
              />

              <span @click="handleClickItem(item, index)" v-show="!item.editing" class="file-name-item">{{
                item.name
              }}</span>
              <icon-edit v-show="!item.editing" @click="handleOpenEdit(item)" class="el-icon-edit" />
            </div>
            <a-button
              v-show="
                (currentTask.status == 3 || currentTask.status == 6 || currentTask.status == 7) && taskType == 'edit'
              "
              @click="handleAddFile"
              size="small"
            >
              <template #icon>
                <icon-plus />
              </template>
              添加
            </a-button>
          </div>
          <div class="title-line-right flex-justify-between" :class="{ 'head-flod': !expand.right }">
            <span class="expand-icon">
              <icon-menu-fold
                style="transform: rotate(180deg)"
                v-show="expand.right"
                class="el-icon-s-unfold"
                @click="expand.right = false"
              />
              <icon-menu-unfold
                style="transform: rotate(180deg)"
                v-show="!expand.right"
                class="el-icon-s-fold"
                @click="expand.right = true"
              />
            </span>
            <span class="title-name">任务信息</span>
          </div>
        </div>
        <a-spin style="width: 100%; height: calc(100% - 50px)" :loading="submitLoading" tip="提交中。。。">
          <div class="approved-body">
            <div class="container-left" ref="dragLeftContent" :class="{ 'content-flod': !expand.left }">
              <div style="right: 0" ref="dragLeft" class="drag-box drag-left"></div>
              <div class="content-info scrollbar-class" v-show="expand.left">
                <a-timeline :reverse="isReverse">
                  <a-timeline-item
                    :type="isAllChecked == false && ind == 0 && 'primary'"
                    placement="top"
                    v-for="(item, ind) in versionList"
                    :key="item.id"
                    :label="item.create_time"
                  >
                    <!-- 文件名列表 -->
                    <div
                      class="time-line-content"
                      v-for="(item2, index2) in item.text_url.filter(
                        (dd, dindex) => currentFileIndex == null || dindex === currentFileIndex
                      )"
                    >
                      <div class="file-time-line flex-justify-between">
                        <span style="color: #aaa">{{ item.create_time }}</span>
                        <span class="file-info file-status-will" v-if="item.status === '待撰写'">{{
                          item.status
                        }}</span>
                        <a-tag color="orangered" v-if="item.status === '客户驳回'">{{ item.status }}</a-tag>
                        <a-tag color="orangered" v-if="item.status === '主管驳回'">{{ item.status }}</a-tag>
                        <a-tag color="green" v-if="item.status === '已通过'">{{ item.status }}</a-tag>
                        <a-tag color="blue" v-if="item.status === '待审核'">{{ item.status }}</a-tag>
                        <!-- <span class="file-info file-status" v-else>{{ item.status }}</span> -->
                      </div>
                      <div
                        class="file-info"
                        style="
                          margin-top: 4px;
                          width: min-content;
                          white-space: nowrap;
                          max-width: 100%;
                          text-overflow: ellipsis;
                          overflow: hidden;
                        "
                        @click="handleClickFile(item2, index2, ind)"
                      >
                        <i class="el-icon-document"></i>
                        <span style="margin-left: 2px" class="file-name">{{ item2.name }}</span>
                      </div>
                    </div></a-timeline-item
                  >
                </a-timeline>
              </div>
            </div>
            <div class="container-center">
              <div
                class="button-body"
                v-show="
                  (currentTask.status == 3 || currentTask.status == 6 || currentTask.status == 7) &&
                  taskType == 'edit' &&
                  currentFileIndex != null
                "
              >
                <a-button @click="saveDraft">保存草稿</a-button>
                <a-button style="margin-left: 8px" @click="handleDelete">删除当前稿件</a-button>
                <a-button style="margin-left: 8px" @click="handleSubmitAll" type="primary">提交审核</a-button>
              </div>
              <div
                style="display: flex; align-items: center; padding: 8px"
                v-show="
                  (currentTask.status == 3 || currentTask.status == 6 || currentTask.status == 7) &&
                  taskType == 'edit' &&
                  currentFileIndex != null
                "
              >
                <!-- <div
                id="upload-box"
                class="upload-box"
                v-if="taskType === 'edit' && currentFileList.text_url[currentFileIndex]?.url"
              >
                <div class="file-left">
                  <i class="el-icon-document"></i>
                </div>
                <div class="file-right">
                  <span class="file-name">{{ currentFileList.text_url[currentFileIndex]?.name }}</span>
                </div>
                <icon-close @click.stop="beforeRemove" id="delete-file" class="el-icon-close delete-file" />
              </div> -->
                <a-upload
                  style="width: 400px"
                  ref="upload"
                  v-if="currentFileIndex !== null"
                  :auto-upload="false"
                  :file-list="fileUploadList"
                  class="upload-demo"
                  name="wordfile"
                  accept=".docx"
                  action="/"
                  :limit="1"
                  @change="handleChangeFile"
                >
                  <template #upload-button>
                    <a-button style="line-height: 30px; margin-left: 4px" type="primary">选择Word文件</a-button>
                    <span style="color: #aaa; font-size: 12px; margin-left: 4px">只能上传.docx文件</span>
                  </template>
                </a-upload>
              </div>
              <div class="container-editor scrollbar-class" v-loading="loadingFile">
                <!-- <div
                style="height: 100%; width: 1200px; margin: 0 auto; background: #fff; padding: 24px"
                v-show="
                  (currentTask.status == 3 || currentTask.status == 6 || currentTask.status == 7) &&
                  taskType == 'edit' &&
                  currentFileIndex != null
                "
                id="editor"
              ></div> -->
                <a-spin style="width: 1200px; display: block; margin: 0 auto" :loading="loadingFile" tip="加载中。。。">
                  <Editor
                    style="width: 100%; height: 900px; margin: 0 auto"
                    v-show="
                      (currentTask.status == 3 || currentTask.status == 6 || currentTask.status == 7) &&
                      taskType == 'edit' &&
                      currentFileIndex != null
                    "
                    v-model="currentEditor"
                  ></Editor>
                  <div
                    style="width: 100%; height: 900px; margin: 0 auto; background: #fff; padding: 24px"
                    class="center-body scrollbar-class"
                    v-show="
                      taskType !== 'edit' ||
                      (currentTask.status != 3 && currentTask.status != 6 && currentTask.status != 7)
                    "
                  >
                    <iframe
                      class="scrollbar-class"
                      :srcdoc="currentTextInfo"
                      width="100%"
                      height="100%"
                      frameborder="0"
                      allowfullscreen
                    ></iframe>
                  </div>
                </a-spin>
              </div>
              <div class="button-body" v-if="taskType === 'audit' && currentTask.status == 4">
                <a-button @click="openEdit">驳回修改</a-button>
                <a-button style="margin-left: 8px" @click="handleApprove" type="primary">审核通过</a-button>
              </div>
            </div>
            <div ref="dragRihtContent" class="container-rihgt" :class="{ 'content-flod': !expand.right }">
              <div style="left: 0" ref="dragRiht" class="drag-box drag-rihgt"></div>
              <div class="content-info" v-show="expand.right">
                <a-tabs v-model:active-key="activeName" class="demo-tabs" @change="handleClickTab">
                  <a-tab-pane key="关键词" title="关键词">
                    <div class="key-word-content">
                      <div class="key-word-item" v-for="(item, index) in keywordsList" :key="index">
                        <div class="key-word-item-header flex-justify-between">
                          <div class="key-word-item-header-left">
                            <div class="item-header-left-text">提出时间</div>
                            <span>{{ item.createTime }}</span>
                          </div>
                          <div class="key-word-item-header-right">
                            <span>提出人：</span>
                            <span class="persion">{{ item.persion }}</span>
                            <span
                              class="key-word-item-role"
                              :class="{ 'key-word-item-role-client': item.role === '用户' }"
                              >{{ item.role }}</span
                            >
                          </div>
                        </div>
                        <div class="key-word-item-content">
                          <p>关键词</p>
                          <div class="key-word-item-content-item">
                            {{ item.keyWord }}
                          </div>
                        </div>
                      </div>
                    </div>
                  </a-tab-pane>
                  <a-tab-pane key="修改意见" title="修改意见">
                    <a-timeline :reverse="isReverse">
                      <a-timeline-item
                        :type="isAllChecked == false && ind == 0 && 'primary'"
                        placement="top"
                        v-for="(item, ind) in editList"
                        :key="key"
                        :label="item.createTime"
                      >
                        <div class="key-word-item">
                          <div class="key-word-item-header flex-justify-between">
                            <div class="key-word-item-header-left">
                              <div class="item-header-left-text">提出时间</div>
                              <span>{{ item.createTime.split(' ')[1] }}</span>
                            </div>
                            <div class="key-word-item-header-right">
                              <span>提出人：</span>
                              <span>{{ item.persion }}</span>
                              <span
                                class="key-word-item-role"
                                :class="{ 'key-word-item-role-client': item.role === '用户' }"
                                >{{ item.role }}</span
                              >
                            </div>
                          </div>
                          <div style="margin-top: 12px">
                            <div
                              class="suggestion-container scrollbar-class"
                              style="overflow: overlay"
                              v-html="item.keyWord"
                            ></div>
                          </div></div
                      ></a-timeline-item>
                    </a-timeline>
                  </a-tab-pane>
                  <a-tab-pane key="审核意见" title="审核意见">
                    <div class="approve-box" v-show="taskType === 'audit' && currentTask.status == 4">
                      <Editor
                        style="height: 300px"
                        :toolbarKeys="[]"
                        palceholder="请填写驳回理由（必填）"
                        v-model="rejectContent"
                      ></Editor>
                      <!-- <p style="font-size: 12px; color: #999">请填写驳回理由（必填）</p> -->
                      <!-- <div ref="rejectRef" id="editorReject"></div> -->
                      <div class="operation-button">
                        <!-- <el-button size="small" @click="dialogVisible = false">取消</el-button> -->
                        <a-button
                          :disabled="!rejectContent || rejectContent == '<p><br></p>'"
                          type="primary"
                          style="margin: 12px 0"
                          size="small"
                          @click="rejectInfo"
                          >确认驳回</a-button
                        >
                      </div>
                    </div>
                    <a-timeline :reverse="isReverse">
                      <a-timeline-item
                        :type="isAllChecked == false && index == 0 && 'primary'"
                        placement="top"
                        v-for="(item, index) in approveList"
                        :key="index"
                        :label="item.createTime"
                      >
                        <div class="key-word-item">
                          <div class="key-word-item-header flex-justify-between">
                            <div class="key-word-item-header-left">
                              <div class="item-header-left-text">审核时间</div>
                              <span>{{ item.createTime.split(' ')[1] }}</span>
                            </div>
                            <div class="key-word-item-header-right">
                              <span>提出人：</span>
                              <span class="persion">{{ item.persion }}</span>
                            </div>
                          </div>
                          <div style="margin-top: 12px">
                            <div
                              class="suggestion-container scrollbar-class"
                              style="overflow: overlay"
                              v-html="item.keyWord"
                            ></div>
                          </div>
                        </div>
                      </a-timeline-item>
                    </a-timeline>
                  </a-tab-pane>
                  <a-tab-pane key="客户需求" title="客户需求">
                    <div class="key-word-content">
                      <div class="key-word-item">
                        <div class="key-word-item-header flex-justify-between">
                          <div class="key-word-item-header-left">
                            <div class="item-header-left-text">需求类型</div>
                            <span>{{ customerDemandList?.demandType }}</span>
                          </div>
                        </div>
                        <div class="key-word-item-content">
                          <p>需求说明:</p>
                          <div class="key-word-item-content-item">
                            {{ customerDemandList?.keyWord }}
                          </div>
                        </div>
                      </div>
                      <div
                        id="upload-box"
                        @click="handleOpenDemandFile"
                        style="cursor: pointer"
                        class="upload-box"
                        v-if="customerDemandList.annex_url"
                      >
                        <div class="file-left">
                          <icon-file />
                        </div>
                        <div class="file-right">
                          <span class="file-name">{{ customerDemandList.annex_url?.name }}</span>
                        </div>
                      </div>
                    </div>
                  </a-tab-pane>
                </a-tabs>
              </div>
            </div>
          </div>
        </a-spin>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts" name="DataDetail">
import { ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  getMyTaskListPost,
  queryFilieList,
  queryDraftList,
  queryContent,
  uploadFile,
  getKeyWordList,
  handleSubmitApprove,
  keywordListUpdate
} from '@/apis'
import { format } from 'date-fns'
import { Message } from '@arco-design/web-vue'
import mammoth from 'mammoth'
import Editor from './ItmopWangEditor/editorFile.vue'
import axios from 'axios'
import { Modal } from '@arco-design/web-vue'
import htmlDocx from 'html-docx-js/dist/html-docx'

const route = useRoute()
const router = useRouter()
const currentEditor = ref('') //当前富文本编辑内容
const rejectContent = ref('') //驳回理由
const fileUploadList = ref([])
let taskId = route.query.id || ''
let taskType = route.query.type || ''
let currentTask = ref({})
const expand = ref({
  left: false,
  right: false
})

const defaultExpandkeys = ref([])
if (taskType == 'edit') {
  defaultExpandkeys.value = ['1']
}
const submitLoading = ref(false)
// 版本列表
const versionList = ref([])
const currentFileList = ref({
  file_url: [],
  text_url: [],
  imag_url: []
})
const currentFeil = ref({})
const isAllChecked = ref(true)
const currentFeilActive = ref({})
const currentFileIndex = ref(null)
const currentTextInfo = ref('')
const customerDemandList = ref({})

const handleChangeAll = (val) => {
  currentFileIndex.value = null
}
const handleGoBackList = () => {
  router.back()
}
const userInfo = ref({
  username: '/',
  userPhone: '/',
  taskId: '/',
  auditStatus: '/',
  taskStatus: '/',
  cancelTime: '/',
  createTime: '/',
  demandName: '/',
  executive: '/'
})
// 右侧数据
const activeName = ref('关键词')
const keywordsList = ref([])
const editList = ref([])
const approveList = ref([])
const computedEdtList = computed(() => {
  return editList.value.reduce((acc, curr) => {
    // 获取当前条目的创建日期，形如 "2022-01-01"
    let createDate = curr.createTime.split(' ')[0]

    // 如果之前没有该日期分组，则创建一个新的分组
    if (!acc[createDate]) {
      acc[createDate] = []
    }

    // 将当前条目加入相应的日期分组中
    acc[createDate].push(curr)

    return acc
  }, {})
})
const computedApproveList = computed(() => {
  return editList.value.reduce((acc, curr) => {
    // 获取当前条目的创建日期，形如 "2022-01-01"
    let createDate = curr.createTime.split(' ')[0]

    // 如果之前没有该日期分组，则创建一个新的分组
    if (!acc[createDate]) {
      acc[createDate] = []
    }

    // 将当前条目加入相应的日期分组中
    acc[createDate].push(curr)

    return acc
  }, {})
})

const initTaskDetail = async () => {
  const statusMap2 = {
    1: '待审核关键词',
    2: '关键词审核不通过',
    3: '待小编撰写',
    4: '待主管审核稿件',
    5: '待用户确认稿件',
    6: '主管驳回待小编撰写',
    7: '用户驳回待小编撰写',
    8: '已完成',
    0: '已取消'
  }
  let res = await getMyTaskListPost({
    admin_pc: 1,
    keyword_id: taskId,
    status_in: '0,1,2,3,4,5,6,7,8'
  })
  let result = JSON.parse(res)

  currentTask.value = result.result?.data?.[0] || {}
  console.log(currentTask.value)

  let customer = currentTask.value?.Customer || {}
  let executive = currentTask.value?.EmpowerAdmin || {}
  let DemandList = currentTask.value?.DemandList || {}
  userInfo.value.username = customer.nickname
  userInfo.value.userPhone = customer.mobile?.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2')
  userInfo.value.taskId = taskId
  userInfo.value.status = currentTask.value.status
  // userInfo.value.auditStatus = statusMap2[currentTask.value.stauts];
  userInfo.value.taskStatus = statusMap2[currentTask.value.status]
  userInfo.value.username = customer.nickname
  userInfo.value.createTime = currentTask.value.create_time
  userInfo.value.demandName = currentTask.value.DemandList?.name
  userInfo.value.executive = executive.remarks
  let repeat_map = {
    1: '重复任务',
    2: '单次任务'
  }
  const type_map = {
    1: '日交',
    2: '周交'
  }
  let annex_url = DemandList.annex_url?.trim()
  if (annex_url) {
    try {
      annex_url = JSON.parse(annex_url)
    } catch {
      annex_url = {
        src: annex_url,
        name: '文件'
      }
    }
  }
  customerDemandList.value = {
    ...DemandList,
    demandType: repeat_map[DemandList.repeat] + (DemandList.repeat == 1 ? `/${type_map[DemandList.type]}` : ''),
    keyWord: DemandList.descript || '',
    annex_url: annex_url
  }
  getFileList()
}

const handleAddFile = () => {
  let len = currentFileList.value.text_url.length
  currentFileList.value.text_url?.push({
    name: '文件名' + (len + 1)
  })
  currentFileList.value.file_url?.push({
    name: '文件名' + (len + 1)
  })
}
// 查询草稿
const viewDraft = async () => {
  let res = await queryDraftList(
    {
      keyword_id: taskId
    },
    'check'
  )
  let result = JSON.parse(res)
  let statusMap = {
    1: '待审核',
    2: '主管驳回',
    3: '客户驳回',
    4: '已通过'
  }
  let resData = result.result || {}
  let text_url = JSON.parse(resData.text_url || '[]')
  let file_url = JSON.parse(resData.file_url || '[]')
  if (text_url.length === 0) {
    //否则根据待撰写稿件篇数创建文件列表
    currentFileList.value = {
      file_url: [],
      text_url: [],
      imag_url: []
    }
    for (let index = 0; index < (currentTask.value.manuscripts_num || 0); index++) {
      handleAddFile()
    }
  } else {
    currentFileList.value = {
      text_url,
      imag_url: [],
      file_url
    }
  }
  handleClickItem(currentFileList.value.text_url[0], 0)
}
// 上传文件
const fileUploadFn = (formData) => {
  return new Promise(async (resolve, reject) => {
    let res = await uploadFile(formData)
    let fileUrl = ''
    if (import.meta.env.MODE === 'development') {
      // 本地联调时使用
      fileUrl = 'https://push.aiseoword.com/'
    } else {
      // 线上环境使用
      fileUrl = import.meta.env.VITE_UPLOADED_FILE_BASE_URL
    }
    // let result = JSON.parse(res)
    resolve({ ...res, baseURL: fileUrl })
  })
}
// 保存当前编辑的富文本并转换word文档
const handleSaveCurrentPage = () => {
  return new Promise((resolve, reject) => {
    let file = currentFileList.value.text_url[currentFileIndex.value] || {}
    let curHtml = currentEditor.value
    if (curHtml && curHtml !== '<p><br></p>') {
      const blob = new Blob([curHtml], { type: 'text/html' })
      const formData = new FormData()
      formData.append('file', blob, `${file.name}.html`)
      fileUploadFn(formData).then(async (res) => {
        if (res.code === 200) {
          currentFileList.value.text_url[currentFileIndex.value] = {
            url: res.baseURL + res.src,
            name: file.name,
            size: file.size
          }
          // // 保存当前编辑的富文本并转换word文档
          // let wordurl = await htmlToWord(curHtml, file)
          // currentFileList.value.file_url[currentFileIndex.value] = {
          //   url: wordurl.url,
          //   name: wordurl.name
          // }
          resolve()
        } else {
          Message.error(res.msg || '文件上传失败！')
        }
        reject()
      })
    } else {
      resolve()
    }
  })
}
const handleClickItem = async (item, index, flag = true, isSlider) => {
  // 切换前需要先保存一下当前编辑的内容(编辑状态下)
  if (
    (currentTask.value.status == 3 || currentTask.value.status == 6 || currentTask.value.status == 7) &&
    taskType == 'edit' &&
    currentFileIndex.value !== null &&
    !isSlider
  ) {
    await handleSaveCurrentPage()
  }
  if (item.url) {
    // let result = await queryContent(item.url)
    let result = await axios.get(item.url)
    currentTextInfo.value = result.data || ''
    currentEditor.value = result.data || ''
    // 回显上传按钮
    fileUploadList.value = [
      {
        uid: '-1',
        name: item.name,
        url: item.url
      }
    ]
  } else {
    currentEditor.value = ''
    currentTextInfo.value = ''
    fileUploadList.value = []
  }
  //获取文章内容
  if (currentFileList.value.text_url.length > 1) {
    isAllChecked.value = false
  } else {
    isAllChecked.value = true
  }
  if (flag) {
    currentFileIndex.value = index
  }
}
// 获取文件列表
const getFileList = async () => {
  if (taskType === 'edit') {
    viewDraft()
  }
  let res = await queryFilieList({
    keyword_id: taskId,
    switch: 5
  })
  let result = JSON.parse(res)
  console.log(result)

  let statusMap = {
    1: '待审核',
    2: '主管驳回',
    3: '客户驳回',
    4: '已通过'
  }
  let resData = result.result || []
  if (resData.length > 0) {
    versionList.value = resData.map((dd) => {
      return {
        ...dd,
        // file_url: JSON.parse(dd.file_url),
        text_url: JSON.parse(dd.text_url),
        // imag_url: JSON.parse(dd.imag_url),
        status: statusMap[dd.status]
      }
    })
    if (taskType !== 'edit') {
      currentFileList.value = versionList.value[0]
    }
  } else {
    if (taskType !== 'edit') {
      //否则根据待撰写稿件篇数创建文件列表
      currentFileList.value = {
        file_url: [],
        text_url: [],
        imag_url: []
      }
      for (let index = 0; index < (currentTask.value.manuscripts_num || 0); index++) {
        handleAddFile()
      }
    }
  }
  if (taskType !== 'edit') {
    handleClickItem(currentFileList.value.text_url[0], 0)
  }
}
const loadingFile = ref(false)
//上传文件
const handleChangeFile = (_, currentFile) => {
  const file = currentFile.file
  if (!file || !_.length) {
    currentFileList.value.text_url[currentFileIndex.value] &&
      (currentFileList.value.text_url[currentFileIndex.value].url = '')
    return
  }
  loadingFile.value = true
  //上传转html
  var reader = new FileReader()
  reader.onload = function (event) {
    var arrayBuffer = event.target.result
    try {
      mammoth
        .convertToHtml({ arrayBuffer: arrayBuffer }, { ignoreElement: (element) => element.name === 'w:alt' })
        .then((res) => {
          console.log(res)

          if (res.value) {
            const blob = new Blob([res.value], { type: 'text/html' })
            const formData = new FormData()
            formData.append('file', blob, `${file.name}.html`) // 'file' is the key name for the file
            fileUploadFn(formData).then((res) => {
              loadingFile.value = false
              if (res.code === 200) {
                currentFileList.value.text_url[currentFileIndex.value] = {
                  url: res.baseURL + res.src,
                  name: file.name,
                  size: file.size
                }
                // 上传成功后回显
                handleClickItem(currentFileList.value.text_url[currentFileIndex.value], currentFileIndex.value)
              } else {
                Message.error(res.msg || '文件上传失败！')
              }
            })
          } else {
            loadingFile.value = false
            Message.error('未防止重复写入，请编辑后上传！')
          }
        })
        .catch(function (err) {
          loadingFile.value = false
          Message.error('文件上传失败，请检查文件格式！')
          console.log('转换错误: ', err)
        })
    } catch (err) {
      loadingFile.value = false
      Message.error('文件上传失败，请检查文件格式！')
    }
  }
  reader.readAsArrayBuffer(file)
}
// 获取关键词列表
const initKeywordsList = async () => {
  let res = await getKeyWordList({
    keyword_id: taskId,
    status_in: '1',
    num: 10000
  })
  let result = JSON.parse(res)
  keywordsList.value = (result.result?.data || []).map((dd) => {
    return {
      createTime: dd.create_time,
      persion:
        dd.operator_type == 1 ? dd.Customer.mobile?.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2') : dd.Admin.remarks,
      keyWord: dd.keyword,
      role: dd.operator_type == 1 ? '用户' : '客服'
    }
  })
}
// 获取修改意见列表
const initEditList = async () => {
  let res = await getKeyWordList({
    keyword_id: taskId,
    status_in: '7',
    num: 10000
  })
  let result = JSON.parse(res)
  editList.value = (result.result?.data || []).map((dd) => {
    return {
      createTime: dd.create_time,
      persion:
        dd.operator_type == 1 ? dd.Customer.mobile?.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2') : dd.Admin.remarks,
      keyWord: dd.detailed,
      role: dd.operator_type == 1 ? '用户' : '客服'
    }
  })
}
// 获取审核意见列表
const initApproveList = async () => {
  let res = await getKeyWordList({
    keyword_id: taskId,
    status_in: '6',
    num: 10000
  })
  let result = JSON.parse(res)
  approveList.value = (result.result?.data || []).map((dd) => {
    let persion = ''
    if (dd.operator_type == 1) {
      //用户
      persion = dd.Customer.mobile?.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2')
    } else if (dd.operator_type == 2) {
      //客服
      persion = dd.Admin.remarks
    }
    return {
      createTime: dd.create_time,
      persion: persion,
      keyWord: dd.detailed,
      role: dd.operator_type == 1 ? '用户' : '客服'
    }
  })
}

const initFn = () => {
  initTaskDetail()
  initKeywordsList()
}
const dragLeft = ref(null)
const dragRiht = ref(null)
const dragLeftContent = ref(null)
const dragRihtContent = ref(null)
const dragFun = (dragBar, dragLeftContent, flag = 'left') => {
  let isDragging = false

  dragBar.addEventListener('mousedown', function (e) {
    isDragging = true
  })

  document.addEventListener('mousemove', function (e) {
    if (!isDragging) return

    const containerRect = document.querySelector('.approved-container').getBoundingClientRect()
    let containerLeft = containerRect.left
    if (flag === 'right') {
      containerLeft = containerRect.right
    }
    const containerWidth = containerRect.width

    const mouseX = e.clientX

    let leftPanelWidth = Math.abs(mouseX - containerLeft)
    let rightPanelWidth = containerWidth - leftPanelWidth - 16 // 减去 dragBar 的宽度
    if (flag === 'right') {
      rightPanelWidth = containerWidth - leftPanelWidth
    }
    if (leftPanelWidth < 350) {
      leftPanelWidth = 350
    }
    dragLeftContent.style.width = leftPanelWidth + 'px'
  })

  document.addEventListener('mouseup', function (e) {
    isDragging = false
  })
}
const handleClickTab = (val) => {
  switch (val) {
    case '修改意见':
      initEditList()
      break
    case '审核意见':
      initApproveList()
      break
    case '客户需求':
      initTaskDetail()
      break
    default:
      initKeywordsList()
      break
  }
}
// 保存草稿
const saveDraft = (type) => {
  currentFileList.value.text_url = currentFileList.value.text_url.map((dd) => ({ name: dd.name, url: dd.url }))
  return new Promise(async (resolve, reject) => {
    if (type !== 'isDelete') {
      await handleSaveCurrentPage()
    }

    let text_url = JSON.stringify(currentFileList.value.text_url)
    // let file_url = JSON.stringify(currentFileList.value.file_url)

    let params = { keyword_id: taskId, text_url }
    let res = await queryDraftList(params, 'save')
    let result = JSON.parse(res)
    if (result.code == 200) {
      if (type !== 'submit') {
        Message.success(result.message || '保存草稿成功！')
      }
      resolve()
      viewDraft()
    } else {
      Message.error(result.message || '保存草稿失败')
    }
  })
}

function convertStyleToWidth(htmlString, containerWidth) {
  // 定义正则表达式以匹配样式中的百分比宽度
  const regex = /style\s*=\s*"[^"]*width\s*:\s*(\d+)%[^"]*"/gi

  // 替换函数
  return htmlString.replace(regex, (match, percentage) => {
    // 计算宽度
    const width = (containerWidth * parseFloat(percentage)) / 100
    // 返回新的宽度属性
    return `width="${width}"`
  })
}
const handleDownload = () => {
  let updatedHtml = currentEditor.value.replace(
    /style="width:\s*(\d+\.?\d*)px;\s*height:\s*(\d+\.?\d*)px;"/g,
    (match, width, height) => {
      return `width="${width}" height="${height}"`
    }
  )
  const updatedHtml2 = convertStyleToWidth(updatedHtml, 1200)

  const newUrl = `<div style="width: 1200px;">${updatedHtml2}</div>`
  // 将HTML内容转换为Word文档
  var converted = htmlDocx.asBlob(newUrl)
  console.log(updatedHtml)

  var a = document.createElement('a')
  a.href = URL.createObjectURL(converted)
  a.download = 'test.docx'
  a.click()
}
const htmlToWord = (html, file, index) => {
  return new Promise((resolve, reject) => {
    try {
      // 将HTML内容转换为Word文档
      // var converted = htmlDocx.asBlob(html)
      const updatedHtml = html.replace(
        /style="width:\s*(\d+\.?\d*)px;\s*height:\s*(\d+\.?\d*)px;"/g,
        (match, width, height) => {
          return `width="${width}" height="${height}"`
        }
      )
      // const newUrl = `<div style="width: 1200px;">${updatedHtml}</div>`
      const updatedHtml2 = convertStyleToWidth(updatedHtml, 1200)
      // 将HTML内容转换为Word文档
      var converted = htmlDocx.asBlob(updatedHtml2)
      var formData = new FormData()
      formData.append('file', converted, `${file.name}.docx`)
      fileUploadFn(formData).then((res) => {
        // console.log('word上传',res);
        if (res.code === 200) {
          resolve({
            url: res.baseURL + res.src,
            name: file.name,
            size: file.size
          })
        } else {
          Message.error(res.msg || 'word上传失败')
          reject(file.name + 'word上传失败')
        }
      })
    } catch (err) {
      reject(file.name + 'word上传失败')
    }
  })
}
// 删除当前稿件
const handleDelete = () => {
  if (currentFileList.value.text_url.length == 1) {
    Message.warning('至少保留一个文件！')
    return
  }
  currentFileList.value.text_url.splice(currentFileIndex.value, 1)
  saveDraft('isDelete').then((res) => {
    //删除成功，默认选中第一项
    currentFileIndex.value = 0
    handleClickItem(currentFileList.value.text_url[0])
  })
}
// 将文件转word和图片并上传
const convertToWordAndImage = (result, item) => {
  return new Promise((resolve, reject) => {
    // 创建一个 Promise 数组
    const promiseA2 = [
      // htmlToImage(result, item).then(imgUrl => ({ imgUrl })),
      htmlToWord(result, item).then((wordUrl) => ({ wordUrl }))
    ]

    // 使用 Promise.all 等待所有 Promise 完成
    Promise.all(promiseA2)
      .then((results) => {
        // 从 results 数组中解构出 imgUrl 和 wordUrl
        // const [{ imgUrl }, { wordUrl }] = results;
        const [{ wordUrl }] = results

        // 创建一个包含这些 URL 的对象
        const output = { wordUrl }

        // 解析 Promise，返回包含 URL 的对象
        resolve(output)
      })
      .catch((err) => {
        // 如果有任何 Promise 失败，则拒绝整个 Promise
        reject(err)
      })
  })
}
//获取html文件接口
const queryHtml = (item) => {
  return new Promise(async (resolve, reject) => {
    // let result = await axios.get(item.url)
    let result = await queryContent(item.url)
    resolve(result.data || '')
  })
}
// 将html转word和图片
const queryLoadingWordAndImage = () => {
  return new Promise(async (resolve, reject) => {
    let imag_url = []
    // let file_url = []
    // 遍历每个链接
    for (const item of currentFileList.value?.text_url || []) {
      if (!item.url) {
        Message.error(`${item.name}文件为空,请补充！`)
        submitLoading.value = false
        reject()
        return
      }
      //拿到当前html富文本内容
      // let htmlContent = await queryHtml(item)
      let result = await axios.get(item.url)
      //分别拿到对应的word和image
      // 假设convertToWordAndImage是异步函数，返回{ wordUrl, imgUrl }
      const { wordUrl } = await convertToWordAndImage(result.data, item)
      // imag_url.push(imgUrl)
      file_url.push(wordUrl)
    }
    currentFileList.value.file_url = file_url
    currentFileList.value.imag_url = imag_url
    resolve()
  })
}
// 提交审核
const handleSubmitAll = () => {
  Modal.confirm({
    content: '确认提交当前内容进行审核?',
    okText: '确认',
    cancelText: '取消',
    onCancel: () => {
      console.log('cancel')
    },
    onOk: async () => {
      // 判断文件长度是否与稿件一致
      if (currentFileList.value.text_url.length < currentTask.value.manuscripts_num) {
        Message.error('文件数量不能低于稿件数量！')
        return
      }

      // 保存当前页面的内容

      //调用一次保存草稿//暂时注释
      await saveDraft('submit')
      submitLoading.value = true
      // 遍历每个链接
      for (const item of currentFileList.value?.text_url || []) {
        if (!item.url) {
          Message.error(`${item.name}文件为空,请补充！`)
          submitLoading.value = false
          return
        }
      }
      // 生成对应数量的word和image
      // let file_url1 = []
      // let imag_url1 = []
      // currentFileList.value.text_url.forEach((item) => {
      //   file_url1.push({
      //     name: item.name,
      //     url: ''
      //   })
      //   imag_url1.push({
      //     name: item.name,
      //     url: ''
      //   })
      // })
      // currentFileList.value.file_url = file_url1
      // currentFileList.value.imag_url = imag_url1
      // queryLoadingWordAndImage()//在切换时就保存了
      //   .then(async (res) => {

      let text_url = JSON.stringify(currentFileList.value.text_url)
      // let file_url = JSON.stringify(currentFileList.value.file_url)
      // let imag_url = JSON.stringify(currentFileList.value.imag_url)
      let params = { keyword_id: taskId, text_url }
      let resData = await handleSubmitApprove(params)
      let result = JSON.parse(resData)
      if (result.code == 200) {
        submitLoading.value = false
        Message.success(result.message || '提交审核成功！')
        handleGoBackList()
      } else {
        Message.error(result.message || '提交失败！')
      }

      submitLoading.value = false
      // })
      // .catch((err) => {
      //   console.log(err)
      // })
    }
  })
}
const changeFileNameRef = ref()
const handleOpenEdit = (item) => {
  currentFileList.value.text_url.forEach((dd) => {
    dd.editing = false
  })
  item.editing = true
  // (changeFileNameRef.value || []).forEach(element => {
  //   element?.focus()
  // });
}
const handleClickFile = (item, index2, index) => {
  let curIndex = currentFileList.value.text_url.findIndex((dd) => dd.name == item.name)
  if (curIndex === -1) {
    //如果名字无法匹配则用index
    handleClickItem(item, index2, true, true)
  } else {
    handleClickItem(item, curIndex, true, true)
  }
}
const handleEditBlur = (item) => {
  item.editing = false
  fileUploadList.value[0].name = item.name
}
const openEdit = () => {
  expand.value.right = true
  activeName.value = '审核意见'
  handleClickTab('审核意见')
}
const rejectRef = ref(false)
// 驳回稿件
const rejectInfo = async () => {
  let res = await keywordListUpdate(
    {
      keyword_id: taskId,
      detailed: rejectContent.value
    },
    'manuscript_rejected'
  )
  let result = JSON.parse(res)

  if (result.code === 200) {
    Message.success(result.message || '驳回成功！')
    rejectContent.value = ''
    handleGoBackList()
  } else {
    Message.error(result.message || '驳回失败！')
  }
}
// 审核通过
const handleApprove = () => {
  Modal.confirm({
    title: '确定是否通过审核？',
    content: '审核通过后将发送给用户',
    okText: '确认',
    cancelText: '取消',
    onCancel: () => {},
    onOk: async () => {
      let res = await keywordListUpdate(
        {
          keyword_id: taskId
        },
        'manuscript_ok'
      )
      let result = JSON.parse(res)
      if (result.code === 200) {
        Message.success(result.message || '审核通过成功！')
        handleGoBackList()
      } else {
        Message.error(result.message || '审核失败！')
      }
    }
  })
}
const handleOpenDemandFile = () => {
  customerDemandList.value?.annex_url?.src && window.open(customerDemandList.value?.annex_url?.src)
}
onMounted(() => {
  dragFun(dragLeft.value, dragLeftContent.value)
  dragFun(dragRiht.value, dragRihtContent.value, 'right')
})
initFn()
</script>

<style lang="scss" scoped>
#upload-box {
  display: flex;
  padding: 8px;
  border-radius: 4px;
  background: #f4f5f5;
  width: 200px;
}
#upload-box .file-left {
  width: 24px;
  height: 24px;
  background: #d3d0d0;
  border-radius: 4px;
  text-align: center;
  line-height: 24px;
  font-size: 16px;
  color: #fff;
}
.file-right {
  color: #333;
  font-weight: bold;
  width: 150px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-left: 4px;
  font-size: 12px;
  line-height: 24px;
}
.delete-file {
  color: #333;
  cursor: pointer;
}
p {
  display: block;
  margin-block-start: 1em;
  margin-block-end: 1em;
  margin-inline-start: 0px;
  margin-inline-end: 0px;
  unicode-bidi: isolate;
}
.scrollbar-class {
  overflow: overlay;
  &::-webkit-scrollbar {
    width: 6px;
    height: 6px;
    background: transparent;
  }

  &::-webkit-scrollbar-thumb {
    background: transparent;
    border-radius: 4px;
  }

  &:hover::-webkit-scrollbar-thumb {
    background: hsla(0, 0%, 53%, 0.4);
  }

  &:hover::-webkit-scrollbar-track {
    background: hsla(0, 0%, 53%, 0.1);
  }
}
.detail {
  overflow: auto;
  height: 100%;
  // display: flex;
  // flex-direction: column;
  .head {
    background: var(--color-bg-1);
  }
  .item {
    margin: $margin;
    background: var(--color-bg-1);
    border-radius: 2px;
  }
  .approve-content {
    height: calc(100% - 20px);
    margin: 10px;
    display: flex;
    flex-direction: column;
    :deep(.arco-collapse-item-header-title) {
      width: calc(100% - 40px);
    }
    .header-line {
      width: 100%;
      display: flex;
      justify-content: space-between;
    }
    .task-detail {
      display: flex;
      flex-wrap: wrap;
      padding: 0 20px;
      margin-top: 16px;
    }

    .task-detail .detail-item {
      width: 20%;
      font-size: 14px;
      display: flex;
      margin-bottom: 8px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .task-detail .detail-item .item-title {
      color: #999;
      margin-right: 4px;
    }
    .approved-container {
      flex: 1;
      height: 0;
      margin-top: 12px;
      background: #fff;
      .expand-icon {
        cursor: pointer;
      }
      .flex-justify-between {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      .center-header {
        flex: 1;
        width: 0;
        height: 50px;
        border-bottom: 1px solid var(--color-border-2);
        padding: 16px 16px 0 16px;
        box-sizing: border-box;
        display: flex;
        overflow: overlay;
        .header-item {
          align-items: center;
          display: flex;
        }
      }

      .center-header > div {
        padding: 0 16px;
        color: #999;
        cursor: pointer;
      }
      .center-header > .active-file {
        color: rgb(var(--link-6));
      }
      .title-line {
        width: 350px;
        height: 50px;
        box-sizing: border-box;
        border-bottom: 1px solid var(--color-border-2);
        padding: 16px 0 0 16px;
      }
      .title-line-right {
        /* width: 350px; */
        width: 416px;
        height: 50px;
        padding: 16px 16px 0 0;
        font-weight: bold;
        box-sizing: border-box;
        border-bottom: 1px solid var(--color-border-2);
      }
      .title-name {
        font-weight: bold;
        margin-right: 24px;
      }
      .content-flod {
        width: 0 !important;
        transition: all 0.3s;
        overflow: hidden;
        position: relative;
      }
      .head-flod {
        width: 120px !important;
        justify-content: flex-start;
      }
      .head-flod .title-name {
        margin-right: 0 !important;
      }
      .file-name-item {
        display: inline-block;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        max-width: 78px;
      }
      .approved-body {
        display: flex;
        // height: calc(100% - 50px);
        height: 100%;
        overflow: overlay;
      }

      .container-left {
        width: 350px;
        height: 100%;
        position: relative;
        overflow: auto;
      }

      .container-center {
        width: 0;
        flex: 1;
        display: flex;
        flex-direction: column;
        position: relative;
        height: 100%;
        overflow: overlay;
      }
      .container-editor {
        width: 100%;
        min-height: calc(100% - 56px);
        /* height: calc(100% - 56px); */
        overflow: overlay;
        background: #f2f2f2;
        box-sizing: border-box;
        padding: 20px 20px 68px 20px;
      }
      .button-body {
        position: absolute;
        bottom: 40px;
        left: 50%;
        transform: translateX(-50%);
        z-index: 9;
      }
      .button-body .el-button {
        padding: 0 20px;
      }

      .approved-container .container-center .center-body {
        flex: 1;
        overflow: overlay;
      }

      .center-header {
        height: 50px;
        border-bottom: 1px solid var(--color-border-2);
        padding: 16px 16px 0 16px;
        box-sizing: border-box;
        display: flex;
        overflow: overlay;
      }

      .center-header > div {
        padding: 0 16px;
        color: #999;
        cursor: pointer;
      }
      .file-name-item {
        display: inline-block;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        max-width: 78px;
      }

      .center-header > .active-file {
        color: rgb(var(--link-6));
      }

      .title-line {
        height: 50px;
        box-sizing: border-box;
        border-bottom: 1px solid var(--color-border-2);
        padding: 16px 0 0 16px;
      }

      .content-info {
        padding: 16px;
        height: 100%;
        box-sizing: border-box;
        overflow: overlay;
      }
      .container-rihgt {
        /* width: 350px; */
        width: 416px;
        position: relative;
      }
      .key-word-item {
        background: #f2f2f2;
        border-radius: 4px;
        margin-bottom: 12px;
        padding: 10px;
        font-size: 12px;
      }
      .key-word-item-header-left {
        border: 1px solid rgb(var(--link-6));
        border-radius: 4px;
        color: rgb(var(--link-6));
        display: flex;
        align-items: center;
      }
      .item-header-left-text {
        background: rgb(var(--link-6));
        color: #fff;
        padding: 2px 4px;
      }
      .key-word-item-header-left > span {
        padding: 0 4px;
      }
      .key-word-item-header-right {
        color: #999;
        white-space: nowrap;
      }
      .persion {
        max-width: 83px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      .key-word-item-role {
        display: inline-block;
        background-color: rgb(188, 238, 217);
        color: black;
        padding: 2px 4px;
        border-radius: 4px;
        margin-left: 8px;
        white-space: nowrap;
      }
      .key-word-item-role-client {
        white-space: nowrap;
        background-color: rgb(188, 220, 238);
      }
      .key-word-item-content > p {
        font-weight: bold;
      }
      .key-word-item-content > div {
        padding: 8px;
        background-color: #fff;
        border-radius: 4px;
        overflow: overlay;
      }

      .time-line-content {
        background: #f7f7f7;
        border-radius: 4px;
        padding: 10px;
        margin-bottom: 12px;
        font-size: 12px;
      }

      .file-info {
        border: 1px solid rgb(var(--link-6));
        border-radius: 4px;
        color: rgb(var(--link-6));
        padding: 4px;
        cursor: pointer;
      }

      .file-status-will {
        background: rgb(var(--link-6));
        padding: 4px;
        border-radius: 4px;
        color: #fff;
        cursor: pointer;
      }

      .file-name {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      .button-body {
        display: flex;
        width: 100%;
        position: absolute;
        z-index: 9;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        background: #fff;
        justify-content: center;
        padding: 8px;
      }
      .drag-box {
        width: 16px;
        position: absolute;
        cursor: col-resize; /* 设置鼠标样式为水平调整大小 */
        height: 100%;
        z-index: 3;
      }
      .container-center .center-body {
        flex: 1;
        overflow: overlay;
      }
    }
  }
}
</style>
